package com.kedou.sdk.download;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.app.DownloadManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.text.TextUtils;
import android.view.animation.LinearInterpolator;

import com.kedou.sdk.utils.WL;

import java.io.File;

public class DownloadScheduleTimer extends AsyncTask<Void, Integer, Uri> {

    private static final String TAG = DownloadScheduleTimer.class.getSimpleName();
    private static final int DEFAULT_LOADING_DURATION = 2000;

    private final long downloadId;
    private final DownloadManager downloadManager;
    private final File storageFile;
    private OnDownloadListener mOnDownloadListener;
    private int currentDownloadBytes;

    private ValueAnimator animator;

    public DownloadScheduleTimer(DownloadManager downloadManager, long downloadId, File storageFile) {
        this.downloadManager = downloadManager;
        this.downloadId = downloadId;
        this.storageFile = storageFile;
    }

    public void setOnVersionUpdateListener(OnDownloadListener listener) {
        this.mOnDownloadListener = listener;
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);

        startUpdateProgressAnimator(this.currentDownloadBytes, values[0], values[1]);

        this.currentDownloadBytes = values[0];
    }

    private void startUpdateProgressAnimator(final int lastValue, final int targetValue, final int fixedValue) {
        if (targetValue <= lastValue) {
            if (mOnDownloadListener != null) {
                mOnDownloadListener.onDownloadProgress(downloadId, targetValue, fixedValue);
            }
            return;
        }

        if (animator != null && animator.isRunning()) {
            return;
        }

        animator = ValueAnimator.ofInt(lastValue, targetValue);
        animator.setDuration(DEFAULT_LOADING_DURATION);
        animator.setInterpolator(new LinearInterpolator());
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                final int updateValue = (int) animation.getAnimatedValue();
                final int newProgress = Math.min(updateValue, targetValue);

                if (mOnDownloadListener != null) {
                    mOnDownloadListener.onDownloadProgress(downloadId, newProgress, fixedValue);
                }
            }
        });

        animator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                if(currentDownloadBytes > targetValue){
                    startUpdateProgressAnimator(targetValue, currentDownloadBytes, fixedValue);
                }
            }

        });

        animator.start();
    }

    @Override
    protected void onPostExecute(Uri uri) {
       WL.i(TAG, "onPostExecute ======> uri: " + uri.toString());

        if (mOnDownloadListener != null) {
            mOnDownloadListener.onDownloadCompleted(downloadId, this.storageFile);
        }
    }

    @Override
    protected void onCancelled() {
        super.onCancelled();
        WL.i(TAG, "onCancelled ============> ");

        if (mOnDownloadListener != null) {
            mOnDownloadListener.onDownloadError(downloadId);
        }
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        WL.i(TAG, "onPreExecute ============> ");
        onProgressUpdate(0, 0);
    }

    @Override
    protected Uri doInBackground(Void... voids) {
        clearDownloadedApkFile();

        boolean cancel = false;
        while (!cancel) {
            DownloadInfo downloadInfo = DownloadInfo.queryDownloadInfo(downloadManager, downloadId);

            WL.i(TAG, "doInBackground ============> status: " + downloadInfo.downloadStatus);

            switch (downloadInfo.downloadStatus) {
                case -1:
                    cancel = true;
                    cancel(true);
                    break;

                case DownloadManager.STATUS_PENDING:
                case DownloadManager.STATUS_RUNNING:
                    publishProgress(downloadInfo.downloadedBytes, downloadInfo.downloadTotalBytes);
                    break;

                case DownloadManager.STATUS_SUCCESSFUL:
                    publishProgress(downloadInfo.downloadTotalBytes, downloadInfo.downloadTotalBytes);
                    cancel = true;
                    break;

                case DownloadManager.STATUS_FAILED:
                    cancel = true;
                    cancel(true);
                    break;

                default:
                    cancel = false;
            }

            try {
                Thread.sleep(DEFAULT_LOADING_DURATION);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        return downloadManager.getUriForDownloadedFile(downloadId);
    }

    private void clearDownloadedApkFile(){
        //删除之前下载的文件
        File parent = storageFile.getParentFile();
        String currentFilename = storageFile.getName();

        if (parent != null && parent.exists()) {
            File[] childFiles = parent.listFiles();
            if (childFiles != null && childFiles.length > 0) {
                for (File file : childFiles) {
                    String filename = file.getName();
                    if (filename.endsWith(".apk") && !TextUtils.equals(filename, currentFilename)) {
                        if(file.delete()){
                            WL.i(TAG, "clear downloaded file success. file: " + file.getPath());
                        }
                    }
                }
            }
        }
    }

}
